/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-03-28 08:23:16
 * @LastEditors: voanit
 * @LastEditTime: 2022-04-03 16:20:02
 */
import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import router from "@/router";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: "/dev-api", // url = base url + request url
  // baseURL: "http://ihrm-java.itheima.net", // 设置axios请求的基础的基础地址
  // baseURL: "http://192.168.90.54:9999/", // 设置axios请求的基础的基础地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    // if (store.getters.token) {
    if (getToken()) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 携带请求头token
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    // console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor  响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log(777);
    const res = response.data;
    if (res.success) {
      // 成功
      Message({
        message: res.message || "Success",
        type: "success",
        duration: 5 * 1000,
      });
    } else {
      // 失败
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      //return Promise.reject(new Error(res.message || "Error"));
    }
    return res;
  },
  (error) => {
    // console.dir(error.response.data.code, 8);
    //判断token过期失效问题
    if (error.response.data.code === 10002) {
      /* 
      1-退出功能
      */
      store.dispatch("user/logout");
      // console.log(router, router.currentRoute.fullPath, 56);
      // router.push(`/login?redirect=${this.$route.fullPath}`);
      // router.push("/login?redirect=" + router.currentRoute.fullPath);
      location.reload(); // 刷新页面
      // location.href='';
    }

    // console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
